﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EAIClassLibrary
{
    /// <summary>
    /// Time Stampe Log
    /// </summary>
    [Serializable]
    public class TimeStampLog
    {
        /// <summary>
        /// Internal LogEntity
        /// </summary>
        [Serializable]
        private class LogEntity
        {
            public DateTime ActionTime { get; set; }
            public string ActionName { get; set; }
        }

        private List<LogEntity> _logs = new List<LogEntity>();

        /// <summary>
        /// Create TimeStampeLog
        /// </summary>
        /// <returns></returns>
        public static TimeStampLog CreateTimeStampLog()
        {
            return new TimeStampLog();
        }

        /// <summary>
        /// Add action.
        /// </summary>
        /// <param name="actionName"></param>
        public void AddAction(string actionName)
        {
            _logs.Add(new LogEntity()
            {
                ActionTime = DateTime.Now,
                ActionName = actionName
            });
        }


        /// <summary>
        /// Convert to string
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            StringBuilder sb = new StringBuilder();
            foreach (var item in _logs)
            {
                sb.Append(string.Format("[{0:yyyy-MM-dd HH:mm:ss.fff}]{1}    ", item.ActionTime, item.ActionName));
            }
            return sb.ToString();
        }

        /// <summary>
        /// Save log to DB's ResField5
        /// </summary>
        /// <param name="msgId"></param>
        public void SaveToDB(string msgId)
        {
            Entities context = new Entities(LogManager.ConnectionString);
            var log = context.Table_Log.First(x => x.MsgID == msgId);
            log.ResField5 = ToString();
            context.SaveChanges();
        }
    }
}
